#!/usr/bin/perl
# 2013/09/29 count total association number for each regions

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -i [association file] -o [list of association number]\n";
}

my %opt;
getopts("i:o:", \%opt);
my $FILE_in = $opt{i};
my $FILE_out = $opt{o};

my %peak;
my %background;
my $fh_in = IO::File->new($FILE_in) or die "cannot open $FILE_in: $!";
while($_ = $fh_in->getline()){
	s/\r?\n//;
	my ($peak1, $loc1, $peak2, $loc2, $interaction, $pval, $q) = split /\t/;
	if($peak1 =~ /MACS/){
		$peak{$peak1}++;
	}else{
		$background{$peak1}++;
	}
	if($peak2 =~ /MACS/){
		$peak{$peak2}++;
	}else{
		$background{$peak2}++;
	}
}
$fh_in->close();

my $fh_out = IO::File->new($FILE_out, 'w') or die "cannot write $FILE_out: $!";
foreach my $name(sort {$peak{$b} <=> $peak{$a}} keys %peak){
	$fh_out->print("$name\t$peak{$name}\n");
}
foreach my $name(sort{$background{$b} <=> $background{$a}} keys %background){
	$fh_out->print("$name\t$background{$name}\n");
}
$fh_out->close();
